package cn.pfz.controller;

import cn.pfz.Service.*;
import cn.pfz.annotation.RequiredPermission;
import cn.pfz.domain.*;
import cn.pfz.query.EmployeeQuery;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeSerives ie;

    @Autowired
    private IDepartmentSerives idd;

    @Autowired
    private IRoleSerives ir;

    @Autowired
    private IEmployeeRoleSerives iero;

    @Autowired
    private IPermissionSerives permissionSerives;




    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQuery qo) {
        PageInfo<Employee> list = ie.list(qo);
        List<Department> departments = idd.selectAll();
        model.addAttribute("deptList", departments);
        model.addAttribute("result", list);
        model.addAttribute("qo", qo);
        return "employee/list";
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee department, Long[] ids) {
        department.setDept_id(department.getDept().getId());
        if (department.getId() != null) {
            //删除原有的
            iero.deleteByPrimaryKey(department.getId());
            //修改
            Long eid = department.getId();
            EmployeeRole employeeRole = new EmployeeRole();
            employeeRole.setEmployee_id(eid);
            if (ids != null) {
                for (Long id : ids) {
                    employeeRole.setRole_id(id);
                    iero.insert(employeeRole);
                }
            }
            ie.updateByPrimaryKey(department);
        } else {
            //在关联表中插入
            Long eid = department.getId();
            EmployeeRole employeeRole = new EmployeeRole();
            employeeRole.setEmployee_id(eid);
            if (ids != null) {
                for (Long id : ids) {
                    employeeRole.setRole_id(id);
                    iero.insert(employeeRole);
                }
                ie.insert(department);
            }
        }
        return "redirect:/employee/list";
    }

    @RequiredPermission(name = "员工删除", experssion = "employee:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        ie.deleteByPrimaryKey(id);
        return JsonResult.success(null);
    }

    @RequestMapping("/input")
    public String input(Model model, Long id) {
        List<Department> departments = idd.selectAll();
        model.addAttribute("deptList", departments);
        List<Role> roles = ir.selectAll();
        model.addAttribute("roleList", roles);
        if (id == null) {
            return "employee/input";
        } else {
            Employee employee = ie.selectByPrimaryKey(id);
            model.addAttribute("curremp", employee);
            List<Role> rs = ir.selectByEmployee(id);
            model.addAttribute("selfRoles", rs);
            return "employee/input";
        }

    }


    @RequestMapping("/batchdelete")
    @ResponseBody
    public JsonResult batchdelete(Long[] ids) {


        ie.batchDeleteByEmployeeIds(ids);
        iero.batchDeleteByEmployeeIds(ids);

        return JsonResult.success(null);
    }

    @RequestMapping("/checkName")
    @ResponseBody
    public Map checkName(String username,Long id) {
        HashMap<String, Boolean> map = new HashMap<>();

        Employee employee = ie.selectByUsername(username);

        if (employee==null){
            map.put("valid",true);
        }else {
            map.put("valid",false);
        }
        return map;
    }



//    @RequestMapping("/login")
//    @ResponseBody
//    public JsonResult login(Employee employee, HttpServletRequest session) {
//        session.getSession().invalidate();
//        Employee e = ie.selectByUsername(employee.getUsername());
//        if (e == null) {
//            return JsonResult.erro("用户不存在");
//        } else {
//            if (e.getPassword().equals(employee.getPassword())) {
//                //查询权限
//                List<Permission> permissions = permissionSerives.selectByEmployee(e.getId());
//                //把权限放在session中
//                session.getSession().setAttribute("currentuser", e.getUsername());
//                session.getSession().setAttribute("userpermission", permissions);
//
//                //返回结果
//                return JsonResult.success(null);
//            } else {
//                //密码错误
//                return JsonResult.erro("密码错误");
//            }
//
//        }
//    }


   @RequestMapping("/login")
  @ResponseBody
   public JsonResult login(Employee employee, HttpServletRequest req, String verCode, HttpServletResponse response) {

       String sessionCode = (String) req.getSession().getAttribute("captcha");
       // 判断验证码
       if (verCode==null || !sessionCode.equals(verCode.trim().toLowerCase())) {
           return JsonResult.erro("验证码不正确");
       }
        try{
       UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(employee.getUsername(), employee.getPassword());
       SecurityUtils.getSubject().login(usernamePasswordToken);
    req.getSession().setAttribute("currentuser",employee.getUsername());
    req.getSession().setAttribute("currentuserpassword",employee.getPassword());
 return JsonResult.success(null);
}
catch (UnknownAccountException e){
    return JsonResult.erro("用户名不对");
}catch (IncorrectCredentialsException e){
    return JsonResult.erro("密码不对");
}
   }


    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
//提交一个数据保存到excel的请求 java操作excel文件 需要设定相应头信息
        //在相应头信息里设定保存的文件名 保存类型
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        //操作excel WorkBook
 Workbook workbook=ie.getWrokbook();
 //生成文件
        workbook.write(response.getOutputStream());
    }

//导入中的下载
    @RequestMapping("/export_model")
    public void export_model(HttpServletResponse response) throws IOException {

        response.setHeader("Content-Disposition","attachment;filename=employeemodel.xls");

        Workbook workbook=ie.getWrokbookModel();

        workbook.write(response.getOutputStream());
    }

    //导入 importXls
    @RequestMapping("/importXls")
    public String importXls(MultipartFile file) throws IOException {
        ie.importXls(file);

        return "redirect:/employee/list";
    }

}